package com.rp.system.corn.timer;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rp.common.config.redis.RedisUtil;
import com.rp.common.utils.Week;
import com.rp.common.utils.ModBusCode;
import com.rp.configure.entity.Device;
import com.rp.configure.entity.Gateway;
import com.rp.configure.entity.Operation;
import com.rp.configure.entity.OperationLog;
import com.rp.configure.entity.vo.AlarmVo;
import com.rp.configure.service.*;
import com.rp.data.tcp_ws.server_tcp.ServerHandlerTcp;
import io.netty.channel.Channel;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;

@Component
public class TimingTask {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AlarmService alarmService;
    @Autowired
    DeviceService deviceService;

    @Autowired
    GatewayService gatewayService;
    @Autowired
    OperationService operationService;
    @Autowired
    OperationLogService operationLogService;
    @SneakyThrows
    //秒，分，时，日，月，周，年
    @Scheduled(cron="0 0/10 * * * ?")
    public void executeDataSend() {
    List<AlarmVo> listAlarm=alarmService.getListAlarm();
        for (AlarmVo alarmVo:listAlarm
             ) {
            String operationId = alarmVo.getOperationId();
            String week = alarmVo.getWeek();
            JSON json = JSONUtil.parse(week);
            ArrayList listWeek = json.toBean(ArrayList.class);
            Boolean flag=false;
            for (int i = 0; i <listWeek.size(); i++) {
                if (listWeek.get(i).equals(Week.getDay())){
                    flag=true;
                    break;
                }
            }
            Duration duration = Duration.between(alarmVo.getUpdateTime(), LocalDateTime.now());
            if (flag&&(duration.toMinutes()>alarmVo.getDelayTime())){
                sendMessage(alarmVo,operationId);
            }
        }
    }
    public void sendMessage(AlarmVo alarmVo,String operationId) throws InterruptedException {
        String gatewayId=alarmVo.getGateWayId();
        Set<Map.Entry<Channel, String>> entries = ServerHandlerTcp.mapChannel.entrySet();
        Iterator<Map.Entry<Channel, String>> iterator = entries.iterator();
        while (iterator.hasNext()){
            Map.Entry<Channel, String> next = iterator.next();
            if (next.getValue().equals(gatewayId)){
                Channel key = next.getKey();
                JSON json = JSONUtil.parse(operationId);
                List<String> listWeek = json.toBean(ArrayList.class);
                QueryWrapper<Operation> wrapper = new QueryWrapper<>();
                System.out.println("======="+json.toString());
                wrapper.orderByAsc("rank1").in("id",listWeek);
                List<Operation> list = operationService.list(wrapper);
                System.out.println(list);
                for (Operation op:list
                     ) {
                    OperationLog operationLog = new OperationLog();
                    operationLog.setAlarmName(alarmVo.getAlarmName()).setGatewayId(gatewayId).setGatewayName(alarmVo.getGatewayName()).setOperationBy("sys").setOperation(op.getName());
                    Device device = new Device();
                    device.setId(alarmVo.getDeviceId());
                    switch (op.getAgreement()){
                        case 5:key.writeAndFlush(ModBusCode.writeSingleCoil(op.getSlaveAddress(),op.getStartAddress(),op.getState()));
                            device.setIsHandle(1);
                        deviceService.updateById(device);
                        break;
                    }
                    operationLogService.save(operationLog);
                }
            }
        }
    }
    @SneakyThrows
    //秒，分，时，日，月，周，年
    @Scheduled(cron="0 0/13 * * * ?")
    public void executeIsOnline() {
        QueryWrapper<Gateway> wrapper= new QueryWrapper<>();
        wrapper.eq("type_id","efb3585a526e971fd178b534e4cc8ee3");
        List<Gateway> list = gatewayService.list(wrapper);
        list.forEach(gateway -> {
            Duration duration = Duration.between(gateway.getUpdateTime(),LocalDateTime.now());
            if (duration.toMinutes()>10&&(gateway.getIsOnline()==1)){
                gateway.setIsOnline(0);
                gatewayService.updateById(gateway);
            }
        });
    }
}
